/**
 * 绘制波形图
 *
 * @param {*} audioRef  参数
 */
export function onLoadAudio(audioRef: HTMLMediaElement | null) {
  if (!audioRef) {
    console.error("Audio element not found");
    return;
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const context = new (window.AudioContext || (window as any).webkitAudioContext)();
  const analyser = context.createAnalyser();
  analyser.fftSize = 2048; // 增大 fftSize 提高频域分辨率
  analyser.smoothingTimeConstant = 0.8; // 平滑频谱数据变化

  const source = context.createMediaElementSource(audioRef);
  source.connect(analyser);
  analyser.connect(context.destination);

  const bufferLength = analyser.frequencyBinCount;
  const dataArray = new Uint8Array(bufferLength);

  const canvas = document.getElementById("canvas") as HTMLCanvasElement;
  if (!canvas) {
    console.error("Canvas element not found");
    return;
  }
  const ctx = canvas.getContext("2d")!;
  const WIDTH = canvas.width = window.innerWidth;
  const HEIGHT = canvas.height = window.innerHeight;

  const barWidth = (WIDTH / bufferLength) * 10; // 调整条形宽度以适应屏幕大小
  const barSpacing = 0; // 增加条形之间的间距

  function renderFrame() {
    requestAnimationFrame(renderFrame);

    analyser.getByteFrequencyData(dataArray);

    ctx.clearRect(0, 0, WIDTH, HEIGHT);

    ctx.beginPath();
    let x = 0;

    for (let i = 0; i < bufferLength; i++) {
      const v = dataArray[i] / 255; // 归一化到 0 到 1 的范围
      const y = v * HEIGHT; // 减小波形高度以适应屏幕

      if (i === 0) {
        ctx.moveTo(x, HEIGHT - y);
      } else {
        ctx.lineTo(x, HEIGHT - y);
      }

      x += barWidth + barSpacing;
    }

    ctx.lineTo(WIDTH, HEIGHT);
    ctx.lineTo(0, HEIGHT);
    ctx.closePath();

    // 设置合成操作以实现视觉效果
    ctx.globalCompositeOperation = 'lighter';

    const hue = 200; // 蓝绿色
    const saturation = '100%';
    const lightness = '50%';

    ctx.fillStyle = `hsla(${hue}, ${saturation}, ${lightness}, 0.5)`;
    ctx.fill();
  }

  renderFrame();
}
